package com.tanhua.app.service;

import cn.hutool.core.collection.CollectionUtil;
import com.tanhua.UserHolder;
import com.tanhua.api.db.UserInfoApi;
import com.tanhua.api.mongo.CommentApi;
import com.tanhua.db.UserInfo;
import com.tanhua.mongo.Comment;
import com.tanhua.utils.RelativeDateFormat;
import com.tanhua.vo.CommentVo;
import com.tanhua.vo.PageBeanVo;
import org.apache.dubbo.config.annotation.Reference;
import org.bson.types.ObjectId;
import org.springframework.beans.BeanUtils;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class CommentService {

    @Reference
    private CommentApi commentApi;

    @Reference
    private UserInfoApi userInfoApi;

    public ResponseEntity findInfo(Integer page, Integer pagesize, String publishId) {

        // 分页查询comment的数据
        PageBeanVo pb=commentApi.findInfo(page,pagesize,publishId);
        List<Comment> items = (List<Comment>) pb.getItems();

        List<CommentVo> commentVo = new ArrayList<>();
        if(CollectionUtil.isNotEmpty(items)){
            for (Comment comment : items) {
                // 查询userinfo的数据
                UserInfo userInfo = userInfoApi.findById(comment.getUserId());
                //封装
                CommentVo vo = new CommentVo();
                BeanUtils.copyProperties(userInfo,vo);
                vo.setContent(comment.getContent());
                vo.setCreateDate(RelativeDateFormat.format(new Date(comment.getCreated())));
                vo.setLikeCount(comment.getLikeCount());
                commentVo.add(vo);
            }
        }
        pb.setItems(commentVo);

        // 组装返回
        return ResponseEntity.ok(pb);

    }

    public ResponseEntity saveInfo(String publishId, String content) {
        // 封装可变数据
        Comment comment = new Comment();
        comment.setPublishId(new ObjectId(publishId));
        comment.setCommentType(2);
        comment.setPubType(1);
        comment.setContent(content); //评论的内容
        comment.setUserId(UserHolder.getUser().getId());
        commentApi.save(comment);
        return ResponseEntity.ok(null);
    }
}
